{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Installation\n",
    "! pip install smolagents\n",
    "# To install from source instead of the last release, comment the command above and uncomment the following one.\n",
    "# ! pip install git+https://github.com/huggingface/smolagents.git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Orchestrate a multi-agent system 🤖🤝🤖"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this notebook we will make a **multi-agent web browser: an agentic system with several agents collaborating to solve problems using the web!**\n",
    "\n",
    "It will be a simple hierarchy:\n",
    "\n",
    "```\n",
    "              +----------------+\n",
    "              | Manager agent  |\n",
    "              +----------------+\n",
    "                       |\n",
    "        _______________|______________\n",
    "       |                              |\n",
    "Code Interpreter            +------------------+\n",
    "    tool                    | Web Search agent |\n",
    "                            +------------------+\n",
    "                               |            |\n",
    "                        Web Search tool     |\n",
    "                                   Visit webpage tool\n",
    "```\n",
    "Let's set up this system. \n",
    "\n",
    "Run the line below to install the required dependencies:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install 'smolagents[toolkit]' --upgrade -q"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's login to HF in order to call Inference Providers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from huggingface_hub import login\n",
    "\n",
    "login()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "⚡️ Our agent will be powered by [Qwen/Qwen3-Next-80B-A3B-Thinking](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Thinking) using `InferenceClientModel` class that uses HF's Inference API: the Inference API allows to quickly and easily run any OS model.\n",
    "\n",
    "> [!TIP]\n",
    "> Inference Providers give access to hundreds of models, powered by serverless inference partners. A list of supported providers can be found [here](https://huggingface.co/docs/inference-providers/index)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_id = \"Qwen/Qwen3-Next-80B-A3B-Thinking\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 🔍 Create a web search tool"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For web browsing, we can already use our native [WebSearchTool](https://huggingface.co/docs/smolagents/main/en/reference/default_tools#smolagents.WebSearchTool) tool to provide a Google search equivalent.\n",
    "\n",
    "But then we will also need to be able to peak into the page found by the `WebSearchTool`.\n",
    "To do so, we could import the library's built-in `VisitWebpageTool`, but we will build it again to see how it's done.\n",
    "\n",
    "So let's create our `VisitWebpageTool` tool from scratch using `markdownify`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "import requests\n",
    "from markdownify import markdownify\n",
    "from requests.exceptions import RequestException\n",
    "from smolagents import tool\n",
    "\n",
    "\n",
    "@tool\n",
    "def visit_webpage(url: str) -> str:\n",
    "    \"\"\"Visits a webpage at the given URL and returns its content as a markdown string.\n",
    "\n",
    "    Args:\n",
    "        url: The URL of the webpage to visit.\n",
    "\n",
    "    Returns:\n",
    "        The content of the webpage converted to Markdown, or an error message if the request fails.\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # Send a GET request to the URL\n",
    "        response = requests.get(url)\n",
    "        response.raise_for_status()  # Raise an exception for bad status codes\n",
    "\n",
    "        # Convert the HTML content to Markdown\n",
    "        markdown_content = markdownify(response.text).strip()\n",
    "\n",
    "        # Remove multiple line breaks\n",
    "        markdown_content = re.sub(r\"\\n{3,}\", \"\\n\\n\", markdown_content)\n",
    "\n",
    "        return markdown_content\n",
    "\n",
    "    except RequestException as e:\n",
    "        return f\"Error fetching the webpage: {str(e)}\"\n",
    "    except Exception as e:\n",
    "        return f\"An unexpected error occurred: {str(e)}\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ok, now let's initialize and test our tool!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(visit_webpage(\"https://en.wikipedia.org/wiki/Hugging_Face\")[:500])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Build our multi-agent system 🤖🤝🤖"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have all the tools `search` and `visit_webpage`, we can use them to create the web agent.\n",
    "\n",
    "Which configuration to choose for this agent?\n",
    "- Web browsing is a single-timeline task that does not require parallel tool calls, so JSON tool calling works well for that. We thus choose a `ToolCallingAgent`.\n",
    "- Also, since sometimes web search requires exploring many pages before finding the correct answer, we prefer to increase the number of `max_steps` to 10."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import (\n",
    "    CodeAgent,\n",
    "    ToolCallingAgent,\n",
    "    InferenceClientModel,\n",
    "    WebSearchTool,\n",
    ")\n",
    "\n",
    "model = InferenceClientModel(model_id=model_id)\n",
    "\n",
    "web_agent = ToolCallingAgent(\n",
    "    tools=[WebSearchTool(), visit_webpage],\n",
    "    model=model,\n",
    "    max_steps=10,\n",
    "    name=\"web_search_agent\",\n",
    "    description=\"Runs web searches for you.\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that we gave this agent attributes `name` and `description`, mandatory attributes to make this agent callable by its manager agent.\n",
    "\n",
    "Then we create a manager agent, and upon initialization we pass our managed agent to it in its `managed_agents` argument.\n",
    "\n",
    "Since this agent is the one tasked with the planning and thinking, advanced reasoning will be beneficial, so a `CodeAgent` will work well.\n",
    "\n",
    "Also, we want to ask a question that involves the current year and does additional data calculations: so let us add `additional_authorized_imports=[\"time\", \"numpy\", \"pandas\"]`, just in case the agent needs these packages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "manager_agent = CodeAgent(\n",
    "    tools=[],\n",
    "    model=model,\n",
    "    managed_agents=[web_agent],\n",
    "    additional_authorized_imports=[\"time\", \"numpy\", \"pandas\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's all! Now let's run our system! We select a question that requires both some calculation and research:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = manager_agent.run(\"If LLM training continues to scale up at the current rhythm until 2030, what would be the electric power in GW required to power the biggest training runs by 2030? What would that correspond to, compared to some countries? Please provide a source for any numbers used.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We get this report as the answer:\n",
    "```\n",
    "Based on current growth projections and energy consumption estimates, if LLM trainings continue to scale up at the \n",
    "current rhythm until 2030:\n",
    "\n",
    "1. The electric power required to power the biggest training runs by 2030 would be approximately 303.74 GW, which \n",
    "translates to about 2,660,762 GWh/year.\n",
    "\n",
    "2. Comparing this to countries' electricity consumption:\n",
    "   - It would be equivalent to about 34% of China's total electricity consumption.\n",
    "   - It would exceed the total electricity consumption of India (184%), Russia (267%), and Japan (291%).\n",
    "   - It would be nearly 9 times the electricity consumption of countries like Italy or Mexico.\n",
    "\n",
    "3. Source of numbers:\n",
    "   - The initial estimate of 5 GW for future LLM training comes from AWS CEO Matt Garman.\n",
    "   - The growth projection used a CAGR of 79.80% from market research by Springs.\n",
    "   - Country electricity consumption data is from the U.S. Energy Information Administration, primarily for the year \n",
    "2021.\n",
    "```\n",
    "\n",
    "Seems like we'll need some sizeable powerplants if the [scaling hypothesis](https://gwern.net/scaling-hypothesis) continues to hold true.\n",
    "\n",
    "Our agents managed to efficiently collaborate towards solving the task! ✅\n",
    "\n",
    "💡 You can easily extend this orchestration to more agents: one does the code execution, one the web search, one handles file loadings..."
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
